import pygame
import random

# 定义常量
WINDOW_WIDTH = 800
WINDOW_HEIGHT = 600
SNAKE_BLOCK = 10
SNAKE_SPEED = 15
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
RED = (255, 0, 0)

# 初始化pygame
pygame.init()

# 设置游戏窗口大小
window = pygame.display.set_mode((WINDOW_WIDTH, WINDOW_HEIGHT))
pygame.display.set_caption("小科熊少儿编程")

# 加载支持中文的字体文件
score_font = pygame.font.Font("msyh.ttc", 35)  # 用于得分显示
title_font = pygame.font.Font("msyh.ttc", 35)  # 用于标题显示

# 初始化贪吃蛇的位置和长度
snake_list = []
snake_length = 1
snake_x = WINDOW_WIDTH / 2
snake_y = WINDOW_HEIGHT / 2

# 初始化食物的位置
food_x = round(random.randrange(0, WINDOW_WIDTH - SNAKE_BLOCK) / 10.0) * 10.0
food_y = round(random.randrange(0, WINDOW_HEIGHT - SNAKE_BLOCK) / 10.0) * 10.0

# 游戏主循环
while True:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
            quit()

    # 获取键盘输入
    keys = pygame.key.get_pressed()
    if keys[pygame.K_LEFT]:
        snake_x -= SNAKE_BLOCK
    if keys[pygame.K_RIGHT]:
        snake_x += SNAKE_BLOCK
    if keys[pygame.K_UP]:
        snake_y -= SNAKE_BLOCK
    if keys[pygame.K_DOWN]:
        snake_y += SNAKE_BLOCK

    # 检查贪吃蛇是否撞到边界
    if snake_x >= WINDOW_WIDTH or snake_x < 0 or snake_y >= WINDOW_HEIGHT or snake_y < 0:
        break

    # 更新贪吃蛇的位置
    window.fill(BLACK)
    snake_head = [snake_x, snake_y]
    snake_list.append(snake_head)
    if len(snake_list) > snake_length:
        del snake_list[0]

    # 绘制贪吃蛇
    for segment in snake_list:
        pygame.draw.rect(window, WHITE, [segment[0], segment[1], SNAKE_BLOCK, SNAKE_BLOCK])

    # 绘制食物
    pygame.draw.rect(window, RED, [food_x, food_y, SNAKE_BLOCK, SNAKE_BLOCK])

    # 检查贪吃蛇是否吃到食物
    if snake_x == food_x and snake_y == food_y:
        food_x = round(random.randrange(0, WINDOW_WIDTH - SNAKE_BLOCK) / 10.0) * 10.0
        food_y = round(random.randrange(0, WINDOW_HEIGHT - SNAKE_BLOCK) / 10.0) * 10.0
        snake_length += 1

    # 更新得分显示
    score_surface = score_font.render("得分: " + str(snake_length - 1), True, WHITE)
    score_rect = score_surface.get_rect()
    score_rect.topleft = (10, 10)
    window.blit(score_surface, score_rect)

    # 在右上角显示标题
    title_surface = title_font.render("梁树彧 花样贪吃蛇", True, WHITE)
    title_rect = title_surface.get_rect()
    title_rect.topright = (WINDOW_WIDTH - 10, 10)  # 右上角位置
    window.blit(title_surface, title_rect)

    # 更新游戏界面
    pygame.display.update()

    # 设置游戏速度
    pygame.time.Clock().tick(SNAKE_SPEED)